import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  Dimensions,
  Linking,
  Alert,
  Platform,
} from 'react-native';
import {ScrollView} from 'react-native-gesture-handler';
import IconFont from '../../resource/iconfont';
import {bindActionCreators} from 'redux';
import * as supplierActionCreator from '../../actions/supplier-actions';
import * as orderFormActionCreator from '../../actions/order-form-actions';
import {connect} from 'react-redux';
import FastImage from 'react-native-fast-image';
import _ from 'lodash';
import Rate from '../../components/rate';
import {getRealSize, Touchable} from '../../utils';
import ThemeStyles from '../../styles';
import {SvgUri} from 'react-native-svg';
import BottomSheet, {
  BottomSheetScrollView,
  BottomSheetView,
} from '@gorhom/bottom-sheet';
import ListItem from '../../components/list-item';
import {Calendar} from 'react-native-calendars';
import 'react-native-get-random-values';
import {v4 as uuidv4} from 'uuid';
import SheetHead from '../../components/items/sheet-head';
import ImageZoomModal from '../../components/image-zoom-modal';
import {I18n} from '../../reducers/intl';
import {UserType} from '../../reducers/user';
import Toast from '../../components/toast';

const snapPoints = [-1, 180, 360, 320, 320];

class SupplierScreen extends React.Component {
  static navigationOptions = () => ({
    title: I18n.t('page.title.supplier'),
    headerBackTitleStyle: Platform.OS === 'ios' && {
      height: 0,
      width: 0,
    },
  });

  state = {
    sheetIndex: -1,
    isOpen: false,
    imageModalVisible: false,
    photos: [],
  };

  componentDidMount() {
    const {navigation, supplierActions} = this.props;
    const supplierId = navigation.getParam('supplierId');
    supplierActions.loadSupplier(supplierId);
  }

  onCreateOrder = product => {
    const {supplier, user, navigation, orderFormActions} = this.props;
    if (!user.approved) {
      return Toast.show(I18n.t('toast.noAuth'), {width: 240});
    }
    if ([UserType.technician, UserType.provider].includes(user.type)) {
      return Toast.show(I18n.t('toast.userTypeError'));
    }
    const pid = uuidv4();
    orderFormActions.reset();
    orderFormActions.updateForm({
      seller: {
        ...supplier,
        products: buildProducts(this.props.categories, this.props.supplier),
      },
      buyer: {...user},
      draft: {
        id: product.id,
        product: product.product,
        pid,
      },
      isNew: true,
    });
    orderFormActions.updateProduct({
      product: product.product,
      pid,
    });
    navigation.navigate('OrderFormPatient');
  };

  toggleSheet = index => {
    if (this.state.isOpen && this.state.sheetIndex === index) {
      this.BottomSheet.close();
      this.setState({sheetIndex: -1, isOpen: false});
    } else {
      this.BottomSheet.snapTo(index);
      this.setState({sheetIndex: index, isOpen: true});
    }
  };

  render() {
    const {supplier, categories} = this.props;
    const products = buildProducts(categories, supplier);
    const photos = _.get(supplier, 'album', []);
    return (
      <View style={{flex: 1}}>
        <ScrollView style={{flex: 1}}>
          <View>
            <ProfileCard {...supplier} />
          </View>
          <View style={Styles.menuContainer}>
            <IconMenu
              name="molarcontact"
              title={I18n.t('menu.contact')}
              onSelect={() => this.toggleSheet(1)}
            />
            <IconMenu
              name="molartime"
              title={I18n.t('menu.work')}
              onSelect={() => this.toggleSheet(2)}
            />
            <IconMenu
              name="molaralbum"
              title={I18n.t('menu.album')}
              onSelect={() => this.toggleSheet(3)}
            />
          </View>
          {supplier.intro && (
            <NotifyCard content={supplier.intro} onMore={() => {}} />
          )}

          <View style={Styles.productContainer}>
            <Text style={Styles.productTitle}>
              {I18n.t('form.label.productList')}
            </Text>
            <View style={Styles.productContent}>
              {products.map((p, index) => (
                <ProductCard
                  index={index}
                  onPress={() => this.onCreateOrder(p)}
                  key={`${p.product.id}-${p.product.type}`}
                  {...p}
                />
              ))}
            </View>
          </View>
        </ScrollView>
        <BottomSheet
          ref={ref => {
            this.BottomSheet = ref;
          }}
          style={Styles.sheetContainer}
          index={this.state.sheetIndex}
          handleComponent={() => (
            <SheetHead onClose={() => this.BottomSheet.close()} />
          )}
          snapPoints={snapPoints}>
          {this.state.sheetIndex === 1 && (
            <Contact
              phone={supplier.mobile}
              email={supplier.email}
              tel={supplier.tel}
            />
          )}
          {this.state.sheetIndex === 2 && (
            <CalendarCard dates={_.get(supplier, 'busy_dates', [])} />
          )}
          {this.state.sheetIndex === 3 && (
            <Album
              datas={photos}
              onZoomImage={() =>
                this.setState({
                  imageModalVisible: true,
                  photos: photos.map(p => ({
                    url: p.url,
                  })),
                })
              }
            />
          )}
          {this.state.sheetIndex === 4 && (
            <Notify content={_.get(supplier, 'into', '')} />
          )}
        </BottomSheet>
        <ImageZoomModal
          visible={this.state.imageModalVisible}
          images={this.state.photos}
          onClose={() => this.setState({imageModalVisible: false})}
        />
      </View>
    );
  }
}

const Notify = props => {
  return (
    <BottomSheetView>
      <Text>{props.content}</Text>
    </BottomSheetView>
  );
};

const Album = props => {
  return (
    <BottomSheetScrollView>
      <View style={Styles.albumContainer}>
        {props.datas.map(photo => (
          <Touchable key={photo.id} onPress={() => props.onZoomImage(photo)}>
            <FastImage
              key={uuidv4()}
              style={Styles.albumImage}
              source={{
                priority: FastImage.priority.normal,
                uri: photo.url,
              }}
            />
          </Touchable>
        ))}
      </View>
    </BottomSheetScrollView>
  );
};

const Contact = props => {
  return (
    <BottomSheetView>
      <ListItem label={I18n.t('form.label.email')} extra={props.email} />
      <ListItem
        label={I18n.t('form.label.tel')}
        extra={props.tel}
        onPress={() => OpenUrl(props.tel)}
      />
    </BottomSheetView>
  );
};

const OpenUrl = async url => {
  if (!url) {
    return;
  }
  const supported = await Linking.canOpenURL(`tel:${url}`);
  if (supported) {
    await Linking.openURL(`tel:${url}`);
  } else {
    Alert.alert(`Don't know how to open this URL: ${url}`);
  }
};

const CalendarCard = props => {
  const markedDates = {};
  props.dates.forEach(item => {
    markedDates[item.date] = {
      selected: true,
      selectedColor: 'red',
    };
  });
  return (
    <BottomSheetView style={{flex: 1}}>
      <Calendar
        markedDates={markedDates}
        futureScrollRange={3}
        pastScrollRange={0}
      />
    </BottomSheetView>
  );
};

const buildProducts = (categories, supplier) => {
  const fixProduct = _.get(supplier, 'fixed_products', []);
  const remvProduct = _.get(supplier, 'remv_arch_products', []);
  const fixedProducts = fixProduct.map(p => ({
    ...p,
    product: {
      ...p.product,
      url: categories.fixedproduct.find(fp => fp.id === p.product.id).icon.url,
    },
  }));
  const remvProducts = remvProduct.map(p => ({
    ...p,
    product: {
      ...p.product,
      url: categories.remvarchproduct.find(fp => fp.id === p.product.id).icon
        .url,
    },
  }));
  return [...fixedProducts, ...remvProducts];
};

const IconMenu = props => {
  return (
    <Touchable onPress={() => props.onSelect()}>
      <View style={Styles.menuContent}>
        <IconFont name={props.name} color="#333333" size={getRealSize(48)} />
        <Text style={Styles.menuLabel}>{props.title}</Text>
      </View>
    </Touchable>
  );
};

const ProductCard = props => {
  const size = (Dimensions.get('screen').width - getRealSize(48)) / 3;
  return (
    <Touchable onPress={() => props.onPress()}>
      <View
        style={[
          Styles.productCardContainer,
          {width: size},
          props.index % 3 && {marginLeft: getRealSize(4)},
        ]}>
        <View style={[Styles.productCardImg, {width: size, height: size}]}>
          <SvgUri
            fill={ThemeStyles.Color.primary.color}
            uri={_.get(props, 'product.url', '')}
            width={88}
            height={88}
          />
        </View>
        <Text style={[Styles.productCardTitle, {width: size}]}>
          {_.get(props, 'product.name', '')}
        </Text>
      </View>
    </Touchable>
  );
};

const NotifyCard = props => {
  return (
    <View style={Styles.notifyCardContainer}>
      <Text style={Styles.notifyCardTitle}>{I18n.t('form.title.note')}</Text>
      <Text
        style={Styles.notifyCardContent}
        ellipsizeMode="tail"
        numberOfLines={5}>
        {props.content}
      </Text>
      <Touchable onPress={() => props.onMore()}>
        <Text style={Styles.notifyCardMore}>{I18n.t('form.title.more')}</Text>
      </Touchable>
    </View>
  );
};

const ProfileCard = props => {
  return (
    <View style={Styles.profileCardContainer}>
      <FastImage
        style={{width: 64, height: 64}}
        source={{
          uri: _.get(props, 'avatar.url', ''),
          priority: FastImage.priority.normal,
        }}
        resizeMode={FastImage.resizeMode.contain}
      />
      <View style={Styles.profileCardContent}>
        <Text>{props.vendor_name}</Text>
        <Text>{`${props.country || ''}${props.province || ''}${
          props.city || ''
        }`}</Text>
        <Rate score={Number(props.rate || 0)} readOnly />
      </View>
    </View>
  );
};

const mapStateToProps = state => ({
  appState: state.appState,
  user: state.user,
  categories: state.constant.category,
  supplier: state.supplier,
  orderForm: state.orderForm,
});

const mapDispatchToProps = dispatch => ({
  orderFormActions: bindActionCreators(orderFormActionCreator, dispatch),
  supplierActions: bindActionCreators(supplierActionCreator, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(SupplierScreen);

const Styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 24,
    backgroundColor: 'white',
  },
  albumContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  albumImage: {
    width: getRealSize(80),
    height: getRealSize(80),
    marginLeft: getRealSize(8),
    marginTop: getRealSize(8),
  },
  sheetContainer: {
    borderTopColor: ThemeStyles.Color.line.color,
    borderTopWidth: StyleSheet.hairlineWidth,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 12,
    },
    shadowOpacity: 0.58,
    shadowRadius: 16.0,

    elevation: 24,
  },
  notifyCardContainer: {
    marginHorizontal: getRealSize(15),
    marginVertical: getRealSize(15),
  },
  notifyCardTitle: {
    fontSize: getRealSize(16),
    fontWeight: 'bold',
  },
  notifyCardContent: {
    marginVertical: getRealSize(12),
    color: '#333333',
  },
  notifyCardMore: {
    color: '#007AFF',
    fontWeight: 'bold',
  },
  menuSheetContainer: {},
  menuContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
    paddingHorizontal: getRealSize(15),
  },
  menuContent: {
    alignItems: 'center',
    height: getRealSize(88),
    width: getRealSize(72),
  },
  menuLabel: {
    color: '#333',
    fontSize: getRealSize(12),
    fontWeight: '400',
    flex: 1,
    width: getRealSize(88),
    textAlign: 'center',
  },
  profileCardContainer: {
    flexDirection: 'row',
    padding: getRealSize(20),
    backgroundColor: '#f7f7f7',
    margin: getRealSize(15),
  },
  profileCardContent: {
    marginLeft: getRealSize(8),
  },
  profileCardTitle: {
    color: '#333',
    fontWeight: 'bold',
  },
  profileCardDesc: {},
  productContainer: {
    paddingHorizontal: getRealSize(15),
  },
  productTitle: {
    // height: getRealSize(52),
    color: '#333',
    paddingVertical: getRealSize(12),
    fontSize: getRealSize(22),
    fontWeight: 'bold',
  },
  productContent: {
    flexWrap: 'wrap',
    flexDirection: 'row',
  },
  productCardContainer: {
    backgroundColor: '#F7F7F7',
    marginTop: getRealSize(12),
    alignItems: 'center',
  },
  productCardTitle: {
    flex: 1,
    paddingHorizontal: getRealSize(8),
    paddingBottom: getRealSize(4),
    color: '#333',
    // fontSize: getRealSize(14),
    // textAlign: 'center',
    // backgroundColor: '#999',
  },
  productCardImg: {
    justifyContent: 'center',
    alignItems: 'center',
  },
});
